<template>
  <div class="xtx-search-page">
    <div class="container">
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem>搜索 "{{ $route.query.keyword }}" 的结果：</XtxBreadItem>
      </XtxBread>
      <div class="wrapper">
        <!-- 排序区 -->
        <SearchSort @change-sort="changeSort" />
        <!-- 结果区 -->
        <ul class="goods-list">
          <li v-for="item in list" :key="item.id">
            <GoodsItem :goods="item" />
          </li>
        </ul>
        <div v-if="!total" class="none">
          <img src="../../assets/none.png" alt="" />
          暂无数据
        </div>
        <!-- 分页区 -->
        <XtxPagination v-if="total" :total="total" :page-size="reqParams.pageSize" :current-page="reqParams.page" @current-change="changePager" />
      </div>
    </div>
  </div>
</template>

<script>
import SearchSort from './components/search-sort.vue'
import { reactive, onMounted, ref } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { getSearchGoods } from '@/api/goods'

export default {
  name: 'xtx-search-page',
  components: { SearchSort },
  setup() {
    // 分页切换
    const route = useRoute()
    const reqParams = reactive({
      page: 1,
      pageSize: 20,
      keyword: route.query.keyword,
      sortField: null,
      sortMethod: null
    })
    const list = ref([])
    const total = ref(0)

    const loadData = async () => {
      const { result } = await getSearchGoods(reqParams)
      // console.log(result.pageData)
      list.value = result.pageData.items
      total.value = result.pageData.counts
    }
    onMounted(() => {
      // 获取数据
      loadData()
    })
    // 分页切换
    const changePager = newPage => {
      reqParams.page = newPage
      loadData()
    }

    // 1. 无数据的暂时，根据total判断即可
    // 2. 排序条件改变更新数据
    // 2.1 子组件通过自定义事件传递数据给父组件，拿到排序数据给查询参数重新请求（第一页）即可
    const changeSort = sortParams => {
      reqParams.sortField = sortParams.sortField
      reqParams.sortMethod = sortParams.sortMethod
      reqParams.page = 1
      loadData()
    }
    // 3. 搜索关键字改变更新数据
    // 3.1 监听路由参数的变化，拿着新的关键字且排序需要重置，重新发请求（第一页）即可
    // 3.2 排序组件的排序效果需要重置
    onBeforeRouteUpdate((to, from, next) => {
      reqParams.keyword = to.query.keyword
      reqParams.sortField = null
      reqParams.sortMethod = null
      reqParams.page = 1
      loadData()
      next()
    })

    return { reqParams, list, total, changePager, changeSort }
  }
}
</script>

<style lang="less" scoped>
.none {
  padding: 100px 0;
  text-align: center;
  color: #999;
  img {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    object-fit: contain;
  }
}
.xtx-search-page {
  .wrapper {
    background-color: #fff;
    padding: 0 25px;
    .goods-list {
      display: flex;
      flex-wrap: wrap;
      padding: 0 5px;
      li {
        margin-right: 20px;
        margin-bottom: 20px;
        &:nth-child(5n) {
          margin-right: 0;
        }
      }
    }
  }
}
</style>